package com.github.caijh.mall.upload.service.impl;

import javax.inject.Inject;

import com.github.caijh.mall.constants.Constants;
import com.github.caijh.mall.system.service.SystemAttachmentService;
import com.github.caijh.mall.system.service.SystemConfigService;
import com.github.caijh.mall.upload.service.UploadService;
import com.github.caijh.mall.upload.vo.FileResultVo;
import com.github.caijh.mall.utils.LocalUploadStrategy;
import com.github.caijh.mall.utils.UploadContext;
import com.github.caijh.mall.utils.UploadSpecs;
import com.github.caijh.mall.utils.UploadType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadServiceImpl implements UploadService {

    @Inject
    private SystemConfigService systemConfigService;

    @Inject
    private SystemAttachmentService systemAttachmentService;

    @Override
    public FileResultVo image(MultipartFile multipart, String model, Integer pid) {
        UploadSpecs fileSpecs = new UploadSpecs();
        fileSpecs.setRootPath(systemConfigService.getValueByKey(Constants.UPLOAD_ROOT_PATH_CONFIG_KEY));
        fileSpecs.setModule(model);
        fileSpecs.setUploadType(UploadType.IMAGE);
        fileSpecs.setCompress(false);
        fileSpecs.setExtSupported(systemConfigService.getValueByKey(Constants.UPLOAD_IMAGE_EXT_STR_CONFIG_KEY));
        fileSpecs.setLimitSize(1024 * 1024 * Long.parseLong(systemConfigService.getValueByKey(Constants.UPLOAD_IMAGE_MAX_SIZE_CONFIG_KEY)));

        UploadContext context = new UploadContext(fileSpecs, new LocalUploadStrategy());
        FileResultVo file = context.upload(multipart, fileSpecs);
        //文件入库
        file.setType(file.getType().replace("image/", ""));
        systemAttachmentService.create(file, pid);
        return file;
    }

    @Override
    public FileResultVo file(MultipartFile multipart, String model, Integer pid) {
        UploadSpecs fileSpecs = new UploadSpecs();
        fileSpecs.setRootPath(systemConfigService.getValueByKey(Constants.UPLOAD_ROOT_PATH_CONFIG_KEY));
        fileSpecs.setModule(model);
        fileSpecs.setUploadType(UploadType.FILE);
        fileSpecs.setCompress(false);
        fileSpecs.setExtSupported(systemConfigService.getValueByKey(Constants.UPLOAD_FILE_EXT_STR_CONFIG_KEY));
        fileSpecs.setLimitSize(1024 * 1024 * Long.parseLong(systemConfigService.getValueByKey(Constants.UPLOAD_FILE_MAX_SIZE_CONFIG_KEY)));

        UploadContext context = new UploadContext(fileSpecs, new LocalUploadStrategy());
        FileResultVo file = context.upload(multipart, fileSpecs);
        //文件入库
        file.setType(file.getType().replace("file/", ""));
        systemAttachmentService.create(file, pid);
        return file;
    }

}

